import { canUse } from "mmb";
import { PingRequest, PingReply } from "../../grpc-client/util/status_pb";

import {
  getBgsStatusOp,
  registerBgsStatusOp,
  getOptions
} from "../../grpc-client/grpcAdapter";
import { healthCheck } from "../../proxy/wxpayProxy"
import {PassThrough} from "stream"
import GrpcTypes from "../../grpc-client/grpcTypes";
import es from "event-stream";
import Router from "koa-router";
const router = new Router();

router.get("/_chk/grpc/bgs", async (ctx, next) => {
  let cl = getBgsStatusOp();
  if (!canUse(cl)) {
    cl = registerBgsStatusOp();
  }
  const req = new PingRequest();
  ctx.body = new PassThrough()
  const grpcStream = cl!.ping(getOptions(GrpcTypes.HEALTH));
  grpcStream.write(req);
  grpcStream
    .on("error", (err) => {
      console.log("err from server", err.message);
      ctx.res.write(`err from server:${err.message}\n`)
      ctx.res.end()
    })
    .on("end", () => {
      console.log("closed from server");
      ctx.res.write(`closed from server\n`)
      ctx.res.end()
    })
    .pipe(
      es.mapSync((data: PingReply) => {
        console.log("pong:", data.getPong());
        setTimeout(() => {
          try {
            grpcStream.write(req);
          } catch (e) {
            console.log("write err", e);
          }
        }, 3000);
        return `${data.getPong()}\n`;
      })
    )
    .pipe(ctx.body)
    
});

router.get("/_chk/grpc/wxpay", async (ctx, next) => {
  ctx.body = await healthCheck()
});

export default router;
